#include <stdio.h>

void countingSort(int arr[], int n) {
    int i, j, k, max = arr[0];
    int count[100] = {0};

    // Find the maximum element in the array
    for (i = 1; i < n; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }

    // Count the frequency of each element
    for (i = 0; i < n; i++) {
        count[arr[i]]++;
    }

    // print the count array
    printf("Count array: \n");
    for (i = 0; i <= max; i++) {
        printf("%d ", count[i]);
    }
    printf("\n");

    // Calculate the cumulative sum of the frequency array
    for (i = 1; i <= max; i++) {
        count[i] += count[i - 1];
    }
    for (i = 0; i <= max; i++) {
        printf("%d ", count[i]);
    }
    printf("\n");

    // Sort the array using the count array
    int temp[n];
    for (i = n - 1; i >= 0; i--) {
        k = arr[i]; // 5
        j = count[k] - 1; // 2 - 1 = 1
        temp[j] = k;
        count[k]--;
    }

    for(i = 0; i < n; i++) {
        arr[i] = temp[i];
    }

}


int main() {
    int arr[] = { 10, 7, 8, 9, 1, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);

    countingSort(arr, n);

    printf("Sorted array: \n");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}